﻿using System;
using System.Collections.Generic;
using System.Drawing.Text;
using System.Linq;
using System.Security;
using System.Text;
using AL.DAL;
using AL.DAL.PublicHistoryPage;
using AL.Entity;

namespace AL.Helper
{
    public class CacheHolder
    {

        private static readonly SogoArticleDownloader SogoArticleDownloader = new SogoArticleDownloader();

        /// <summary>
        /// 排序规则 0 - 默认, 1 - 阅读量从大到小, 2 - 点赞数从大到小
        /// </summary>
        public static int OrderType = 0;


        // 获取已知的分类列表
        public static List<string> GetCategories()
        {
            var accounts = GetAccounts();
            var catetories = new List<string>();
            if (accounts != null) catetories = accounts.Select(y => y.ClassName).Distinct().ToList();
            return catetories;
        }


        #region Account

        public static void AddAccount(Account account)
        {
            DAL.PublicAccount.Provider.Add(account);

            _accounts = null;
        }

        public static void DeleteAccount(string openId)
        {
            DAL.PublicAccount.Provider.Del(openId);
            //DAL.PublicArticle.Provider.DelByOpenId(openId);
            //DAL.PublicHistoryPage.Provider.DelByOpenId(openId);

            _accounts = null;
        }

        public static Account GetAccount(string openId)
        {
            var account = DAL.PublicAccount.Provider.GetByOpenId(openId);
            if (account == null || string.IsNullOrEmpty(account.OpenId))
            {
                // 根据搜索网址获取一个公众账号的数据
                var sogoAccountAnylizer = new SogoAccountAnalizer();
                account = sogoAccountAnylizer.GetAccount(string.Format("http://weixin.sogou.com/gzh?openid={0}", openId));

                // 将帐号添加到数据库中
                if (account == null || string.IsNullOrEmpty(account.OpenId))  DAL.PublicAccount.Provider.Add(account);
            }

            return account;
        }

        private static List<Account> _accounts = null; 
        public static List<Account> GetAccounts()
        {
            if (_accounts == null)
            {
                var predicate = new List<Func<KeyValuePair<string, Account>, bool>> {x => x.Key.Length > 0};
                var outPageCount = 0;
                _accounts = DAL.PublicAccount.Provider.Search(predicate, 1, 1000, out outPageCount);
            }
            return _accounts;
        }

        #endregion

        #region HistoryPage

        public static void RefreshHistoryPagesByOpenId(string openId, EnumType.SearchType searchType, string loginCookies)
        {
            GetHistoryPage(openId, searchType, false);
            var historyPage = GetHistoryPage(openId, searchType, false);
            var articles = SogoArticleDownloader.GetArticlesByHistoryPage(historyPage);


            //if (articles.Any())
            //{
            //    // 获取文章统计数
            //    var articleAnalyzer = new ArticleCountsAnalyzer(loginCookies);
            //    foreach (var article in articles)
            //    {
            //        var oArticle = GetArticleCount(article, loginCookies, false);
            //        if (oArticle != null)
            //        {
            //            article.ReadingCount = oArticle.ReadingCount;
            //            article.PraiseCount = oArticle.PraiseCount;
            //        }
            //    }
            //}
        }

        public static HistoryPage GetHistoryPage(string openId, EnumType.SearchType searchType, bool refreshCache)
        {
            //var historyPage = DAL.PublicHistoryPage.Provider.GetByOpenId(openId, pageIndex);
            //if (historyPage != null && refreshCache) DAL.PublicHistoryPage.Provider.DelByOpenId(openId, pageIndex);
            //if (historyPage == null || refreshCache)
            //{
            //    historyPage = SogoArticleDownloader.GetHistoryPage(openId, pageIndex);
            //    historyPage.OpenId = openId;
            //    historyPage.Key = string.Format("{0}_{1}", openId, pageIndex);

            //    DAL.PublicHistoryPage.Provider.Add(historyPage);
            //}

            var cacheKey = string.Format("{0}_{1}", openId, 1);
            var historyPage = CacheHelper.GetCache(cacheKey);
            if (historyPage == null || refreshCache)
            {
                historyPage = SogoArticleDownloader.GetHistoryPage(openId, searchType);
                CacheHelper.SetCache(cacheKey, historyPage);
            }

            if (historyPage != null) return (HistoryPage)historyPage;
            return null;
        }

        #endregion

        #region Article


        public static void ClearArticlesByOpenId(string openId)
        {
            if (string.IsNullOrWhiteSpace(openId) || openId == "root") DAL.PublicArticle.Provider.Clear();
            else DAL.PublicArticle.Provider.DelByOpenId(openId);
        }

        public static List<Article> GetArticles(string openId, int searchType, string loginCookies)
        {
            var pageIndex = 1;
            var articles = new List<Article>();
            var pageSize = 2000;
            if (OrderType == 1)
            {
                // 阅读量从大到小
                articles = DAL.PublicArticle.Provider.GetByOpenId(openId)
                    .OrderByDescending(x => x.ReadingCount)
                    .Skip((pageIndex - 1)*pageSize)
                    .Take(pageSize).ToList();

            }else if (OrderType == 2)
            {
                // 点赞数从大到小
                articles = DAL.PublicArticle.Provider.GetByOpenId(openId)
                    .OrderByDescending(x => x.PraiseCount)
                    .Skip((pageIndex - 1)*pageSize)
                    .Take(pageSize).ToList();
            }
            else
            {
                articles = DAL.PublicArticle.Provider.GetByOpenId(openId)
                    .OrderByDescending(x => x.ArticleCreated)
                    .Skip((pageIndex - 1) * pageSize)
                    .Take(pageSize).ToList();
            }


            if (articles != null && articles.Count < 1)
            {
                // 根据公众号获取文章列表
                var historyPage = GetHistoryPage(openId, EnumType.SearchType.Week, false);
                articles = SogoArticleDownloader.GetArticlesByHistoryPage(historyPage);
            }


            if (!articles.Any()) return articles;

            // 进度统计
            CacheHelper.Articles = articles;
            CacheHelper.MaxCount += articles.Count;
            //CacheHelper.CurrentCount = 0;

            // 获取文章统计数
            var articleAnalyzer = new ArticleCountsAnalyzer(loginCookies);
            foreach (var article in articles)
            {
                //if (article.ReadingCount < 1)
                //{
                //    var articleResult = articleAnalyzer.AnalyzeArticle(article.ArticleURL);
                //    if (articleResult == null) continue;

                //    article.ReadingCount = articleResult.ReadingCount;
                //    article.PraiseCount = articleResult.PraiseCount;
                //}

                //// 保存文章到数据库
                //DAL.PublicArticle.Provider.Add(article);


                GetTotalCount(article, loginCookies);
            }

            return articles;
        }

        private static void GetTotalCount(Article article, string loginCookies)
        {
            var oArticle = GetArticleCount(article, loginCookies, false);
            if (oArticle != null)
            {
                article.ReadingCount = oArticle.ReadingCount;
                article.PraiseCount = oArticle.PraiseCount;
            }

            // 进度统计
            CacheHelper.CurrentCount += 1;
        }


        public static Article GetArticleCount(Article article, string loginCookies, bool refreshCache)
        {
            if (article != null && !string.IsNullOrEmpty(article.ArticleURL))
            {
                var cacheArticle = DAL.PublicArticle.Provider.GetByArticleId(article.ArticleId);
                if (cacheArticle != null && !string.IsNullOrWhiteSpace(cacheArticle.ArticleId))
                {
                    article.ReadingCount = cacheArticle.ReadingCount;
                    article.PraiseCount = cacheArticle.PraiseCount;
                    article.ArticleWithReadingCountURLCreated = cacheArticle.ArticleWithReadingCountURLCreated;
                };

                if (article.ReadingCount < 1 || refreshCache)
                {
                    // WebClient 获取文章中的统计数据
                    var articleAnalyzer = new ArticleCountsAnalyzer(loginCookies);
                    var result = articleAnalyzer.AnalyzeArticle(article.ArticleURL);
                    if (result != null)
                    {
                        article.ReadingCount = result.ReadingCount;
                        article.PraiseCount = result.PraiseCount;
                        article.ArticleWithReadingCountURLCreated = DateTime.Now;
                    }
                }

                // 保存文章到数据库
                if (cacheArticle != null && !string.IsNullOrWhiteSpace(cacheArticle.ArticleId)) DAL.PublicArticle.Provider.Mod(article);
                else DAL.PublicArticle.Provider.Add(article);

                //if (result.IsDeleted) DAL.PublicArticle.Provider.Del(articleId);
            }

            return article;
        }


        public static Article GetArticle(string articleId, string loginCookies)
        {
            var article = DAL.PublicArticle.Provider.GetByArticleId(articleId);

            return GetArticleCount(article, loginCookies, true);
        }

        #endregion

    }
}
